<template>
  <div class="app-container">
    <!-- 搜索区域使用 transition 包裹 -->
    <el-collapse-transition>
      <el-card v-show="isFilterVisible" class="search-wrapper">
        <el-form
          :inline="true"
          :model="selProjectTypeListQuery"
          class="demo-form-inline"
        >
          <el-form-item label="平台类型">
            <el-input
              v-model="selProjectTypeListQuery.name"
              clearable
              placeholder="请输入平台类型"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-collapse-transition>

    <el-card>
      <div>
        <!-- 操作按钮区域 -->
        <div class="table-operations">
          <el-button
            type="primary"
            size="small"
            class="filter-trigger"
            @click="isFilterVisible = !isFilterVisible"
          >{{ isFilterVisible ? "收起" : "检索" }}
            <i
              :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
            />
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="handleAdd"
          >新增</el-button>
          <el-button
            type="warning"
            size="small"
            icon="el-icon-edit"
            @click="handleBatchEdit"
          >修改</el-button>
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            @click="handleBatchDelete"
          >批量删除</el-button>
        </div>

        <!-- 表格 -->
        <el-table
          :data="selProjectTypeLists"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            type="index"
            label="序号"
            width="150"
            align="center"
          />
          <el-table-column
            prop="name"
            label="平台类型"
            align="center"
            width="width"
          />
          <!-- <el-table-column prop="createTime" label="创建时间" align="center">
            <template slot-scope="scope">
              {{ formatCreateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间" align="center">
            <template slot-scope="scope">
              {{ formatCreateTime(scope.row.updateTime) }}
            </template>
          </el-table-column> -->
          <el-table-column align="center" prop="prop" label="操作" width="width">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
              >编辑</el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <el-row :gutter="10" style="margin-top: 20px;" type="flex" justify="end">
        <el-pagination
          background
          :current-page="selProjectTypeListQuery.page"
          :page-sizes="[10, 20, 30, 40,50]"
          :page-size="selProjectTypeListQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="addProjectTypeQuery.id ? '编辑' : '新增'"
      :visible.sync="dialogVisible"
      width="500px"
      @close="handleClose"
    >
      <el-form
        ref="form"
        :model="addProjectTypeQuery"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="平台类型" prop="name">
          <el-input
            v-model="addProjectTypeQuery.name"
            placeholder="请输入平台类型"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selProjectTypeListApi,
  addProjectTypeApi,
  updateProjectTypeByIdApi,
  delProjectTypeByIdsApi
} from '@/api/basic-data'
export default {
  name: 'PlatformType',
  data() {
    return {
      // 添加搜索框显示状态
      showSearch: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: ''
      },
      // 表格数据
      tableData: [
        {
          typeName: '执行类',
          createTime: '2024-03-07 11:17'
        },
        {
          typeName: '广告类',
          createTime: '2024-03-07 11:17'
        }
      ],
      // 总条数
      total: 2,
      // 选中的行
      selectedRows: [],
      // 弹窗显示控制
      dialogVisible: false,
      // 弹窗标题
      dialogTitle: '',
      // 表单数据
      form: {
        typeName: ''
      },

      isFilterVisible: false,
      // 项目类型列表
      selProjectTypeLists: [],
      // 总条数
      total: 0,
      selProjectTypeListQuery: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      // 新增参数
      addProjectTypeQuery: {
        id: '',
        name: ''
      },
      // 表单校验规则
      rules: {
        name: [{ required: true, message: '请输入平台类型', trigger: 'blur' }]
      },
      selectedIds: [] // 新增：选中项的 id 数组
    }
  },
  created() {
    this.selProjectTypeList()
  },
  methods: {
    // 查询项目类型列表
    async selProjectTypeList() {
      const res = await selProjectTypeListApi(this.selProjectTypeListQuery)
      console.log(res)
      this.selProjectTypeLists = res.records
      this.total = res.total
    },
    // 切换搜索面板
    toggleSearch() {
      // 实现搜索面板显示/隐藏逻辑
      this.showSearch = !this.showSearch
    },
    // 表格选择项变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
      this.selectedIds = selection.map((item) => item.id)
    },
    // 新增
    handleAdd() {
      this.resetForm()
      this.dialogVisible = true
    },
    // 编辑
    handleEdit(row) {
      // this.resetForm();
      console.log(row)
      this.addProjectTypeQuery = { ...row }
      console.log(this.addProjectTypeQuery)
      this.dialogVisible = true
    },
    // 重置表单
    resetForm() {
      this.addProjectTypeQuery = {
        id: '',
        name: ''
      }
      // 如果表单已经被验证过，重置验证结果
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          try {
            let res
            if (!this.addProjectTypeQuery.id) {
              // 新增时创建新对象，只传name字段
              const addData = {
                name: this.addProjectTypeQuery.name
              }
              res = await addProjectTypeApi(addData)
            } else {
              // 编辑时传完整对象
              res = await updateProjectTypeByIdApi(this.addProjectTypeQuery)
            }

            if (res.code === 1) {
              this.$message.success(
                `${this.addProjectTypeQuery.id ? '编辑' : '新增'}成功`
              )
              this.dialogVisible = false
              this.resetForm()
              // 刷新列表
              this.selProjectTypeList()
            } else {
              this.$message.error(res.msg)
            }
          } catch (error) {
            console.error('提交表单失败:', error)
            this.$message.error('操作失败，请重试')
          }
        }
      })
    },
    // 关闭弹窗时重置表单
    handleClose() {
      this.resetForm()
    },
    // 批量编辑
    handleBatchEdit() {
      if (this.selectedRows.length !== 1) {
        this.$message.warning('请选择一条记录进行修改')
        return
      }
      this.handleEdit(this.selectedRows[0])
      // this.handleEdit(this.selectedRows[0]);
    },
    // 查询
    handleQuery() {
      this.selProjectTypeListQuery.page = 1
      this.selProjectTypeList()
    },
    // 重置
    resetQuery() {
      this.selProjectTypeListQuery = {
        page: 1,
        pageSize: 10,
        name: ''
      }
      this.selProjectTypeList()
    },
    // 删除单条记录
    handleDelete(row) {
      this.$confirm('确认删除该平台类型吗？', '提示', {
        type: 'warning'
      })
        .then(async() => {
          try {
            const res = await delProjectTypeByIdsApi([row.id])
            if (res.code === 1) {
              this.$message.success('删除成功')
              this.selProjectTypeList()
            } else {
              this.$message.error(res.msg || '删除失败')
            }
          } catch (error) {
            console.error('删除失败:', error)
            this.$message.error('删除失败，请重试')
          }
        })
        .catch(() => {})
    },
    // 批量删除
    handleBatchDelete() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请选择要删除的项目类型')
        return
      }

      this.$confirm(
        `确认删除选中的项目类型吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async() => {
          try {
            const res = await delProjectTypeByIdsApi(this.selectedIds)
            if (res.code === 1) {
              this.$message.success('删除成功')
              this.selectedIds = [] // 清空选中项
              this.selProjectTypeList()
            } else {
              this.$message.error(res.msg || '删除失败')
            }
          } catch (error) {
            console.error('删除失败:', error)
            this.$message.error('删除失败，请重试')
          }
        })
        .catch(() => {})
    },
    // 格式化创建时间
    formatCreateTime(time) {
      if (!time) return ''
      // 找到第二个冒号的位置并截取字符串
      const secondColonIndex = time.indexOf(':', time.indexOf(':') + 1)
      return time.substring(0, secondColonIndex)
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.selProjectTypeListQuery.pageSize = val
      this.selProjectTypeList()
    },
    // 页码改变
    handleCurrentChange(val) {
      this.selProjectTypeListQuery.page = val
      this.selProjectTypeList()
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.table-operations {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-trigger .el-icon-arrow-down {
  margin-left: 5px;
  transition: transform 0.3s;
}

.filter-trigger .el-icon-arrow-down.is-reverse {
  transform: rotate(180deg);
}

.search-wrapper {
  margin-bottom: 16px;
}

.left {
  display: flex;
  align-items: center;
}

.el-button + .el-button {
  margin-left: 8px;
}
</style>
